package com.huaxindata.im.main.share;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.huaxin.common.tools.Log;
import com.huaxin.common.utils.ToastUtil;
import com.huaxin.common.view.avatarimageview.AvatarImageView;
import com.huaxindata.im.R;
import com.huaxindata.im.main.manager.ContactManager;
import com.huaxindata.im.main.manager.UserManager;
import com.huaxindata.im.model.contact.Contact;
import com.huaxindata.im.model.db.MessageStore;
import com.huaxindata.im.model.entity.ChatMessage;
import com.huaxindata.im.model.entity.ChatMessageBody;
import com.huaxindata.im.service.MessageService;
import com.huaxindata.im.service.OnMessageSendListener;

import java.util.List;

/**
 * Created by Administrator on 2017/10/19.
 * 分享界面，主要是用于用户在站点里点击分享按钮，分享站点信息使用
 * 也可以用于其它的分享界面
 * 站点信息以字符患数组的形式通过Intent传到本界面
 */

public class ShareActivity extends AppCompatActivity implements ShareDialogFragement.ShareConfirmListener {
    public static final String TAG = "xxx-ShareActivity";
    private Toolbar               mToolbar;
    private RecyclerView          mRecyclerView;
    private MyAdapter             mAdapter;
    private List<Contact>         mContactList;
    private DividerItemDecoretion mDecoretion;
    //分享的信息数组，mShareMessage[0]为消息类型
    //private String[]              mShareMessage;
    private int                   mMessage_type;
    private ChatMessageBody       messageBody;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_share);
        initView();
        bindToService();
        initData();
    }

    private void initData() {
        Intent intent = getIntent();
        mMessage_type = intent.getIntExtra("message_type", 0);
        messageBody = intent.getParcelableExtra("message");

        //企业用户间发消息
        mContactList = ContactManager.getColleagueList();
        if (mContactList != null || mContactList.size() != 0) {
            mAdapter.notifyDataSetChanged();
        }
    }

    private void initView() {
        mToolbar = (Toolbar) findViewById(R.id.activity_share_toolBar);
        mToolbar.setTitle("分享");
        setSupportActionBar(mToolbar);
        mToolbar.setNavigationIcon(R.mipmap.icon_back_blue);
        mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                onBackPressed();
            }
        });
        mRecyclerView = (RecyclerView) findViewById(R.id.activity_share_contact_list);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mAdapter = new MyAdapter();
        mDecoretion = new DividerItemDecoretion(this);
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.addItemDecoration(mDecoretion);
        mAdapter.setOnItemClickListener(mItemClickListener);
    }

    public OnItemClickListener mItemClickListener = new OnItemClickListener() {
        @Override
        public void onItemClick(View itemView, int position) {
            if (UserManager.getClientId() .equals(mContactList.get(position).getClientId())){
                ToastUtil.showToast("不支持自己发消息给自己");
                return;
            }
            ShareDialogFragement fragement = ShareDialogFragement.newInstance(messageBody, mMessage_type, position, mContactList.get(position).getNickName(), ShareActivity.this);
            fragement.show(getFragmentManager(), "com.huaxin.share");
        }
    };

    @Override
    public void share(int position, String extraText) {
        final ChatMessage message;
        if (mMessage_type == ChatMessageBody.Type.STATION) {
            message = new ChatMessage(ChatMessageBody.Type.STATION, UserManager.getClientId(), mContactList.get(position).getClientId(), System.currentTimeMillis());
        } else if (mMessage_type == ChatMessageBody.Type.SVG) {
            message = new ChatMessage(ChatMessageBody.Type.SVG, UserManager.getClientId(), mContactList.get(position).getClientId(), System.currentTimeMillis());
        }else{
            message=new ChatMessage();
        }
        message.messageBody = messageBody;
        message.read = 1;
        mMessageService.sendMessage("chat/" + message.receiver, message, new OnMessageSendListener() {
            @Override
            public void sendSuccess(ChatMessage hxMessage) {
                Log.e(TAG, "xxxx===========分享成功");
                Toast.makeText(ShareActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
                message.messageState = ChatMessage.Status.SUCCESS;
                MessageStore.insert(hxMessage);
                finish();
            }

            @Override
            public void sendFailure(ChatMessage hxMessage) {
                Log.e(TAG, "xxxx===========分享失败");
                Toast.makeText(ShareActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
                finish();
            }
        });
    }

    private class DividerItemDecoretion extends RecyclerView.ItemDecoration {
        private final int[] ATTRS = new int[]{
                android.R.attr.listDivider
        };
        private Drawable mDivider;

        public DividerItemDecoretion(Context context) {
            final TypedArray a = context.obtainStyledAttributes(ATTRS);
            mDivider = a.getDrawable(0);
            a.recycle();
        }

        @Override
        public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
            final int left = parent.getPaddingLeft();
            final int right = parent.getWidth() - parent.getPaddingRight();

            final int childCount = parent.getChildCount();
            for (int i = 0; i < childCount; i++) {
                final View child = parent.getChildAt(i);
                final RecyclerView.LayoutParams params = (RecyclerView.LayoutParams) child
                        .getLayoutParams();
                final int top = child.getBottom() + params.bottomMargin;
                final int bottom = top + mDivider.getIntrinsicHeight();
                mDivider.setBounds(left, top, right, bottom);
                mDivider.draw(c);
            }
        }

        @Override
        public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView
                .State state) {
            outRect.set(0, 0, 0, mDivider.getIntrinsicHeight());
        }
    }

    private class MyAdapter extends RecyclerView.Adapter<MyViewHolder> {

        private OnItemClickListener mOnItemClickListener;

        public void setOnItemClickListener(OnItemClickListener onItemClickListener) {
            this.mOnItemClickListener = onItemClickListener;
        }

        @Override
        public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater inflater = LayoutInflater.from(ShareActivity.this);
            View view = inflater.inflate(R.layout.activity_share_simple_list_item, parent, false);
            return new MyViewHolder(view);
        }

        @Override
        public void onBindViewHolder(final MyViewHolder holder, final int position) {
            Contact contact = mContactList.get(position);
            holder.mNameTv.setText(contact.getNickName());
            holder.mDutyTv.setText(contact.getDuty());
            contact.showImageIcon(ShareActivity.this, holder.mIcon, holder.mIconExpandTv);
            if (mOnItemClickListener != null) {
                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        mOnItemClickListener.onItemClick(holder.itemView, position);
                    }
                });
            }
        }

        @Override
        public int getItemCount() {
            return mContactList == null ? 0 : mContactList.size();
        }
    }

    private interface OnItemClickListener {
        void onItemClick(View itemView, int position);
    }

    private class MyViewHolder extends RecyclerView.ViewHolder {
        public AvatarImageView mIcon;
        public TextView        mIconExpandTv;
        public TextView        mNameTv;
        public TextView        mDutyTv;

        public MyViewHolder(View itemView) {
            super(itemView);
            initItemView(itemView);
        }

        private void initItemView(View itemView) {
            mIcon = (AvatarImageView) itemView.findViewById(R.id.share_list_item_icon);
            mIconExpandTv = (TextView) itemView.findViewById(R.id.share_list_item_icon_expand);
            mNameTv = (TextView) itemView.findViewById(R.id.share_list_item_name);
            mDutyTv = (TextView) itemView.findViewById(R.id.share_list_item_duty);
        }
    }

    /**
     * 绑定到后台接收消息的service
     */
    private void bindToService() {
        //先启动service,避免app退出service即被杀死
        startService(new Intent(this, MessageService.class));
        Intent intent = new Intent(this, MessageService.class);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }

    private MessageService mMessageService;
    private ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mMessageService = ((MessageService.MyBinder) service).getService();
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mMessageService = null;
        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mMessageService != null) {
            unbindService(mServiceConnection);
        }
    }
}
